package com.demiroot.server;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class ServerSession {
	private String sessionID = null;
	private Server server;
	private Calendar expiry;
	private Map<Object, Object> vars;
	
	public ServerSession(Server server) {
		vars = new HashMap<Object, Object>();
		this.server = server;
		updateExpire();
	}
	
	public void updateExpire() {
		updateExpire(20);
	}
	
	public void updateExpire(int expireInMin) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MINUTE, expireInMin);
		expiry = cal;
	}
	
	//this should be reasonably random
	public String getSessionID() {
		if (sessionID == null) {
			sessionID = ServerUtils.randomMD5();
			if (server.sessionExists(sessionID)) {
				sessionID = null;
				return getSessionID();
			}
		}
		
		return sessionID;
	}
	
	public Calendar getExpiry() {
		return expiry;
	}
	
	public boolean hasExpired() {
		return Calendar.getInstance().after(expiry);
	}
	
	public Object getVar(Object key) {
		return vars.get(key);
	}
	
	public void setVar(Object key, Object value) {
		vars.put(key, value);
	}
	
	public void removeVar(Object key) {
		vars.remove(key);
	}
}
